/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.booting.balancer4j.engine;

import com.gitee.booting.balancer4j.Action;
import com.gitee.booting.balancer4j.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;

/**
 * A useful base class for {@link Predicate} and {@link Expression} implementations
 */
public class ExpressionSupport implements Expression {
    private static final Logger LOG = LoggerFactory.getLogger(ExpressionSupport.class);
    private static final Map<Class<?>, Function<Action, Object>> CONVERTERS = new HashMap<>();

    public boolean matches(Action exchange) {
        Object value = evaluate(exchange, Object.class);
        return ObjectHelper.evaluateValuePredicate(value);
    }

    public Object evaluate(Action action) {
        return evaluate(action, Object.class);
    }

    public void assertMatches(String text, Action action) {
        if (!matches(action)) {
            throw new AssertionError(text + " " + assertionFailureMessage(action) + " for action: " + action);
        }
    }

    protected String assertionFailureMessage(Action action) {
        return action.toString();
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> T evaluate(Action action, Class<T> type) {
        return CONVERTERS.containsKey(type) ? (T) CONVERTERS.get(type).apply(action) : null;
    }

    public static <T> Function<Action, T> register(Function<Action, T> converter) {
        Class<?> key = converter.getClass().getTypeParameters()[1].getGenericDeclaration();
        if (CONVERTERS.containsKey(key)) {
            LOG.warn("Converter of type {} will be replaced to {}", CONVERTERS.get(key), converter);
        }
        CONVERTERS.put(key, (Function<Action, Object>) converter);
        return converter;
    }
}
